﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
namespace ScreenshotCapturer
{
    public static class Config
    {
        public static void writeConfig(DataSet DS_Config)
        {
            System.Configuration.Configuration config =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            DataTable DT = DS_Config.Tables[0];
            config.AppSettings.Settings.Clear();
            foreach (DataRow R in DT.Rows)
            {
                config.AppSettings.Settings.Add(R[0].ToString(), R[1].ToString());
            }
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static bool editConfig(string key, string value)
        {
            bool pass = false;
            System.Configuration.Configuration config =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            DataSet DS_Config = ShowConfig();
            DataTable DT = DS_Config.Tables[0];
            foreach (DataRow R in DT.Rows)
            {
                if (R[0].ToString() == key)
                {
                    R[1] = value.ToString();
                    config.AppSettings.Settings.Clear();
                    foreach (DataRow S in DT.Rows)
                    {
                        config.AppSettings.Settings.Add(S[0].ToString(), S[1].ToString());
                    }
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                    pass = true;
                }
            }
            return pass;
        }
        public static DataSet ShowConfig()//Grab the systems Settings
        {
            try
            {
                // For read access you do not need to call the OpenExeConfiguraton
                DataSet DS_Config = new DataSet();
                DataTable DT = new DataTable();
                DT.Columns.Add("Setting", typeof(System.String));
                DT.Columns.Add("Value", typeof(System.String));
                foreach (string key in ConfigurationManager.AppSettings)
                {
                    string value = ConfigurationManager.AppSettings[key];
                    //Console.WriteLine("Key: {0}, Value: {1}", key, value);
                    DataRow DR = DT.NewRow();
                    DR["Setting"] = key.ToString();
                    DR["Value"] = value.ToString();
                    DT.Rows.Add(DR);
                }
                DS_Config.Tables.Add(DT);
                return DS_Config;
            }
            catch
            {
                return null;
            }
        }
    }
}
